package com.dhms.uikit

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.lifecycleScope
import com.dhms.basebusiness.databinding.ActivityPdfViewerBinding
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Streaming
import retrofit2.http.Url
import java.io.File
import java.io.FileOutputStream

class PdfViewerActivity : AppCompatActivity() {

    private lateinit var _binding: ActivityPdfViewerBinding
    val binding get() = _binding

    private var preToastCoroutine: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        _binding = ActivityPdfViewerBinding.inflate(layoutInflater)
        setContentView(binding.root)

        window?.apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val windowInsetsController = decorView.windowInsetsController
                windowInsetsController?.systemBarsBehavior =
                    WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
                windowInsetsController?.hide(WindowInsets.Type.statusBars())
                setDecorFitsSystemWindows(false)
            } else {
                decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                        )
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            window?.attributes?.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }

        val uri = intent.extras?.getParcelable<Uri>(PDF_FILE_URI_KEY)
        if (uri != null) {
            if (isLocalResource(uri)) {
                loadPdf(uri)
            } else {
                downloadFile(uri.toString())
            }
        } else {
            showToast(
                R.drawable.ic_close,
                message = "文件地址为空！",
                timeOut = 1
            )
        }
    }

    private fun downloadFile(url: String) {
        lifecycleScope.launch {
            try {
                showToast(
                    message = "下载中",
                    isLoading = true,
                    timeOut = 0
                )
                val urlArray = url.split("/")
                val filePreUrl = urlArray.take(urlArray.size - 1).joinToString("/") + "/"
                val fileName = urlArray.last()
                val body =
                    Retrofit.Builder()
                        .baseUrl(filePreUrl)
                        .build().create(NetworkService::class.java)
                        .downloadFile(fileName)

                val saveFileThread = Thread {
                    val file = File(cacheDir, fileName)
                    val fileOutputStream =
                        FileOutputStream(file)
                    fileOutputStream.write(body.bytes())
                    fileOutputStream.close()

                    loadPdf(Uri.fromFile(file))
                    hideToast()
                }
                saveFileThread.start()
            } catch (e: Exception) {
                Log.e(TAG, e.message, e)
                showToast(
                    R.drawable.ic_close,
                    "下载或保存失败",
                    timeOut = 1
                )
            }
        }
    }

    private fun loadPdf(uri: Uri) {
        binding.pdfViewer.fromUri(uri).load()
    }

    fun showToast(
        icon: Int? = null,
        message: String? = null,
        isLoading: Boolean = false,
        timeOut: Int = 3,
        isShowing: Boolean = true
    ) {
        if (icon != null) {
            binding.toast.icon = ResourcesCompat.getDrawable(resources, icon, null)
        }
        binding.toast.message = message
        binding.toast.isLoading = isLoading
        binding.toast.visibility = isShowing
        preToastCoroutine?.cancel()
        if (timeOut != 0) {
            preToastCoroutine = lifecycleScope.launch {
                delay(timeOut * 1000L)
                binding.toast.visibility = false
            }
        } else {
            preToastCoroutine = null
        }
    }

    fun hideToast() {
        preToastCoroutine?.cancel()
        binding.toast.visibility = false
        preToastCoroutine = null
    }

    override fun onBackPressed() {
        ActivityCompat.finishAfterTransition(this)
    }

    companion object {
        const val PDF_FILE_URI_KEY = "PDF_FILE_URI_KEY"

        private const val TAG = "PdfViewerActivity"

        fun startActivity(uri: Uri, activity: Activity) {
            val intent = Intent(
                activity,
                PdfViewerActivity::class.java
            )
            intent.putExtra(PDF_FILE_URI_KEY, uri)
            val optionsCompat =
                ActivityOptionsCompat.makeSceneTransitionAnimation(activity)
            ActivityCompat.startActivity(
                activity,
                intent, optionsCompat.toBundle()
            )
        }

        interface NetworkService {
            @Streaming
            @GET
            suspend fun downloadFile(@Url fileUrl: String): ResponseBody
        }
    }
}